//
//  SIMainController.swift
//  SinaImiate
//
//  Created by xiaoming on 16/6/29.
//  Copyright © 2016年 GoodJob. All rights reserved.
//

import UIKit
import SVProgressHUD

class SIMainController: UITabBarController {
    
    ///定义个时钟,监督微博更新情况
    private var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        
        setupComposeButton()
        
        setupTimer()
        
        setupNewfeatureView()
        
        delegate = self
        
        ///注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: userNeedLoginSinaNotification), object: nil)
        
    }
    
    //MARK: -监听方法
    //FIXME: 没有实现
    ///撰写微博
    @objc private func composeStatus() {
        print("撰写微博")
        
        let v = SIComposeTypeView.composeTypeView()
        
        v .show { [weak self] (clsName) in
            
            print(clsName)
            
            guard let clsName = clsName,
                cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? UIViewController.Type else {
                    v.removeFromSuperview()
                    
                    return
            }
            
            let vc = cls.init()
            let nav = UINavigationController(rootViewController: vc)
            
            nav.view.layoutIfNeeded()
            
            self?.present(nav, animated: true, completion: { 
                v.removeFromSuperview()
            })
            
            
        }
    }
    
    private lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return .portrait
    }
    
    ///销毁时钟
    deinit {
        
        timer?.invalidate()
        
        NotificationCenter.default.removeObserver(self)
    }
    
    //MARK: - 接收到需要登录通知,调用此方法
    @objc private func userLogin(n: Notification) {
        
        print("用户登录通知" + "\(n)")
        
        var when = DispatchTime.now()
        
        if n.object != nil {
            
            SVProgressHUD.setDefaultMaskType(.gradient)
            
            SVProgressHUD.showInfo(withStatus: "用户授权已过期,需要重新授权或登录")
            
            when = when + 1.5
        }
        
        DispatchQueue.main.after(when: when) { 
            
            SVProgressHUD.setDefaultMaskType(.clear)
            
            
            let nav = UINavigationController(rootViewController: SIOAuthViewController())
            
            self.present(nav, animated: true, completion: nil)
            
        }
        
        
    }

}



extension SIMainController {
    
    private func setupTimer() {
        
        timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    @objc private func updateTimer() {
        
        //MARK: 如果不登录,那么不刷新时钟
        if !SINetworkTools.shared.userLogon {
            return
        }
        
        SINetworkTools.shared.unreadCount { (count) in
            print("有" + "\(count)" + "条新微博")
            
            ///显示在程序内部
            self.tabBar.items?[0].badgeValue = count > 0 ? count.description : nil
            
            ///显示在程序图标处
            UIApplication.shared().applicationIconBadgeNumber = count
        }
        
    }
}

extension SIMainController {
    
    private func setupNewfeatureView() {
        
        if !SINetworkTools.shared.userLogon {
            return
        }
        
        let v = isNewVersion ? SINewFeatureView.newFeatureView() : SIWelcomeView.welcomeView()
        
        v.frame = view.bounds
        
        view.addSubview(v)
    }
    
    private var isNewVersion: Bool {
        
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        let path: String = ("version" as NSString).cz_appendDocumentDir()
        
        let sandboxVersion = (try? String(contentsOfFile: path)) ?? ""
        
         _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        return currentVersion != sandboxVersion
    }
}

// MARK: - UITabBarControllerDelegate
extension SIMainController: UITabBarControllerDelegate {
    
    
    /// 判断是否是中间button按钮对应的UIViewController

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
//        print("将要切换到" + "\(viewController)")
        let idx = childViewControllers.index(of: viewController)
        
        if selectedIndex == 0 && idx == selectedIndex {
            
            print("点击首页")
            
            let nav = childViewControllers[0] as! UINavigationController
            
            let vc = nav.childViewControllers[0] as! SIHomeViewController
            
            vc.tableview?.setContentOffset(CGPoint(x: 0, y: -64) , animated: true)
            
            DispatchQueue.main.after(when: DispatchTime.now() + 1, execute: {
                
                vc.loadData()
            })
            
            vc.tabBarItem.badgeValue = nil;
            
            UIApplication.shared().applicationIconBadgeNumber = 0
        }
        
        return !viewController.isMember(of: UIViewController.self)
        
    }
    
}

// MARK: - 撰写按钮
extension SIMainController {
    
    private func setupComposeButton() {
        tabBar.addSubview(composeButton)
        
        let count = CGFloat(childViewControllers.count)
        
        let w = tabBar.bounds.width / count
        
        composeButton.frame = tabBar.bounds.insetBy(dx: w * 2, dy: 0)
        
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        
        
    }
    
    //MARK: 设置所有的子控制器
    private func setupChildControllers() {
//        
//        let array: [[String: AnyObject]] = [
//            ["clsName": "SIHomeViewController", "title": "首页", "imageName": "home", "visitorInfo": ["imageName": "", "message": "关注一些人, 回这里看看有什么惊喜"]],
//            ["clsName": "SIMessageViewController", "title": "消息", "imageName": "message_center", "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]],
//            ["clsName": "UIViewController"],
//            ["clsName": "SIDiscoverViewcontroller", "title": "发现", "imageName": "discover", "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过"]],
//            ["clsName": "SIProfileViewController", "title": "我", "imageName": "profile", "visitorInfo": ["imageName": "visitordiscover_image_profile", "message": "登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]]
//        ]
////        
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        
//        (data as NSData).write(toFile: "/Users/mac/Desktop/demo.json", atomically: true)
        
        guard let path = Bundle.main.pathForResource("demo.json", ofType: nil),
            data = NSData(contentsOfFile: path),
            array = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [[String: AnyObject]] else {
                return
        }
        
        var arrayM = [UIViewController]()
        
        for dict in array! {
            
            arrayM.append(controller(dict: dict))
            
        }
        
        viewControllers = arrayM
        
    }
    
    private func controller(dict: [String: AnyObject]) -> UIViewController {
        
        guard let clsName = dict["clsName"] as? String,
            title = dict["title"] as? String,
            imageName = dict["imageName"] as? String,
            cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? SIBaseViewController.Type,
            visitorDict = dict["visitorInfo"] as? [String: String]
            else {
            return UIViewController()
        }
        
        let vc = cls.init()
        
        vc.title = title
        
        vc.visitorInfoDictonary = visitorDict
        
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange()], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 14)], for: UIControlState(rawValue: 0))
        
        let nav = SINavigationController(rootViewController: vc)
        
        
        return nav
        
        
    }
    
}
